import datetime
from flask import request, jsonify
from flask_jwt_extended import verify_jwt_in_request, get_jwt


def check_token_expiry():
    excluded_paths = [
        '/user/login',
        '/user/refresh',
        '/user/auth2/login',
        '/user/auth2/info',
        '/files/',
        '/form/model',
        '/form/preset',
        '/form/upload',
    ]

    # 检查当前请求路径是否需要token验证
    if any(request.path.startswith(path) for path in excluded_paths):
        return None

    try:
        verify_jwt_in_request()
        jwt_data = get_jwt()
        exp_timestamp = jwt_data.get('exp')

        if exp_timestamp:
            current_timestamp = datetime.datetime.now().timestamp()
            if current_timestamp > exp_timestamp:
                return jsonify({
                    'success': False,
                    'code': 401
                })

    except Exception as e:
        # 如果token验证失败，返回401错误
        return jsonify({
            'success': False,
            'msg': 'Token验证失败，请重新登录',
            'code': 402
        })

    return None
